package com.loongtech.bi.action.birealtime;

import com.loongtech.bi.action.TransferHelper;
import com.loongtech.bi.entity.gameoverview.*;
import com.loongtech.bi.manager.report.GameOverviewManager;
import com.loongtech.bi.manager.report.GameReportManager;
import com.loongtech.bi.manager.system.BiChannelManager;
import com.loongtech.bi.manager.system.ConfigManager;
import com.loongtech.bi.manager.system.SysRoleChannelManager;
import com.loongtech.bi.manager.system.SysUserManager;
import com.loongtech.core.util.Time;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Author: yuri
 * Description: 游戏实时概况
 * Date: 16:41 2017/11/21
 */
@Controller
@Scope("prototype")
@RequestMapping("/bi/gameoverview")
public class GameOverviewAction extends TransferHelper {
    public static final DecimalFormat format = new DecimalFormat(",###");

    @Resource
    private GameReportManager gameReportManager;
    @Resource
    private SysRoleChannelManager sysRoleChannelManager;
    @Resource
    private SysUserManager sysUserManager;
    @Resource
    private GameOverviewManager gameOverviewManager;
    @Resource
    private BiChannelManager biChannelManager;
    @Resource
    private ConfigManager configManager;

    @RequestMapping(value = "search.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String dstart, @RequestParam String dend, String callback) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> result0 = new HashMap<>();
        Map<String, Object> result2 = new HashMap<>();
        Map<String, Object> result3 = new HashMap<>();
        result.put("0", result0);
        result.put("2", result2);
        result.put("3", result3);

        String opendate = configManager.getConfigValueByName(ConfigManager.OPEN_DATE) == null ? "1900-01-01" : configManager.getConfigValueByName(ConfigManager.OPEN_DATE);
        Date openDay = Time.formatDate(opendate, Time.TIMEPATTERN_SIMPLE);
        Date dstartDay = Time.formatDate(dstart, Time.TIMEPATTERN_SIMPLE);
        Date startDay = Time.isBig(dstartDay, openDay) ? dstartDay : openDay;
        Date endDay = Time.formatDate(dend, Time.TIMEPATTERN_SIMPLE);

        Map<String, EntityBanner> entityBanners = new HashMap<>();
        Map<String, List<EntityNewAdd>> newAdds = new HashMap<>();
        Map<String, List<EntityActive>> actives = new HashMap<>();
        Map<String, List<EntityPay>> pays = new HashMap<>();
        Map<String, List<EntityOnline>> onlines = new HashMap<>();
        Map<String, List<EntityDuration>> durations = new HashMap<>();
        Map<String, List<EntityRemain>> remains = new HashMap<>();

        Map<String, EntityChannelSource> channelSources = new HashMap<>();

        try {
            // 取得所有total数据
            Map<String, Map<String, String>> tlist = gameOverviewManager.getTotalDatas2(openDay);

            for (Map.Entry<String, Map<String, String>> entry : tlist.entrySet()) {
                String platformid = entry.getKey();
                Map<String, String> value = entry.getValue();

                EntityBanner entityBanner = new EntityBanner();
                entityBanner.setTotalDeviceActive(value.get("deviceActive"));
                entityBanner.setTotalNewAddPlayer(value.get("newAddPlayer"));
                entityBanner.setTotalActivePlayer(value.get("activePlayer"));
                entityBanner.setTotalPayPlayer(value.get("payPlayer"));
                entityBanner.setTotalPayAmount(value.get("payAmount"));

                entityBanners.put(platformid, entityBanner);
            }

            // 取得所有平台数据
            List<GameReportManager.GameReportData> allData = gameReportManager.getAllGameReportData2(startDay, endDay);

            if (allData != null && allData.size() > 0) {
                int d = Time.getInterval(startDay, endDay);

                List<GameReportManager.GameReportData> platformDataList = new ArrayList<>();
                List<GameReportManager.GameReportData> detailServerDataList = new ArrayList<>();
                List<GameReportManager.GameReportData> detailChannelDataList = new ArrayList<>();
                List<GameReportManager.GameReportData> channelDisplayDataList = new ArrayList<>();

                gameReportManager.updateData2(allData, platformDataList, detailChannelDataList, detailServerDataList);
                for (GameReportManager.GameReportData p : platformDataList) {
                    String platfromid = p.getPlatformId();

                    // 取得首行除total外的其它数据
                    EntityBanner entityBanner = entityBanners.get(platfromid);
                    if (entityBanner != null) {
                        entityBanner.setActivePlayer(d > 59 ? "-" : format.format(p.getActiveUserCount()));
                        entityBanner.setDeviceActive(format.format(p.getActiveDevice()));
                        entityBanner.setNewAddPlayer(format.format(p.getNewUser()));
                        entityBanner.setPayAmount(format.format(p.getPayCount()));
                        entityBanner.setPayPlayer(d > 59 ? "-" : format.format(p.getPayUserCount()));
                    }

                    // 取得平台相关所有图表数据
                    List<EntityNewAdd> newAddList = newAdds.get(platfromid);
                    if (newAddList == null) {
                        newAddList = new ArrayList<>();
                        newAdds.put(platfromid, newAddList);
                    }
                    List<EntityActive> activeList = actives.get(platfromid);
                    if (activeList == null) {
                        activeList = new ArrayList<>();
                        actives.put(platfromid, activeList);
                    }
                    List<EntityPay> payList = pays.get(platfromid);
                    if (payList == null) {
                        payList = new ArrayList<>();
                        pays.put(platfromid, payList);
                    }
                    List<EntityOnline> onlineList = onlines.get(platfromid);
                    if (onlineList == null) {
                        onlineList = new ArrayList<>();
                        onlines.put(platfromid, onlineList);
                    }
                    List<EntityDuration> durationList = durations.get(platfromid);
                    if (durationList == null) {
                        durationList = new ArrayList<>();
                        durations.put(platfromid, durationList);
                    }
                    List<EntityRemain> remainList = remains.get(platfromid);
                    if (remainList == null) {
                        remainList = new ArrayList<>();
                        remains.put(platfromid, remainList);
                    }
                    List<GameReportManager.GameReportData> detailPlatformDisplayData = p.getTogglerDatas();
                    for (GameReportManager.GameReportData gameReportData : detailPlatformDisplayData) {
                        EntityNewAdd newAdd = new EntityNewAdd();
                        newAdd.setDeviceActive(gameReportData.getActiveDevice());
                        newAdd.setActiveAddRadio(gameReportData.getActive2NewRadio());
                        newAdd.setDateStr(gameReportData.getDateStr());
                        newAddList.add(newAdd);

                        EntityActive active = new EntityActive();
                        active.setAllAcu(gameReportData.getActiveUserCountByDay());
                        active.setNewAcu(gameReportData.getNewUser());
                        active.setOldAcu(active.getAllAcu() - gameReportData.getNewUser());
                        active.setDateStr(gameReportData.getDateStr());
                        activeList.add(active);

                        EntityPay pay = new EntityPay();
                        pay.setPayAmount(gameReportData.getPayCount());
                        pay.setPayPlayer(gameReportData.getPayUserCountByDay());
                        pay.setActivePayRadio(gameReportData.getActivePayRadio());
                        pay.setARPU(gameReportData.getActiveARPU());
                        pay.setARPPU(gameReportData.getPayARPU());
                        pay.setDateStr(gameReportData.getDateStr());
                        payList.add(pay);

                        EntityOnline online = new EntityOnline();
                        online.setDau(gameReportData.getActiveUserCountByDay());
                        online.setAcu(gameReportData.getAcu());
                        online.setPcu(gameReportData.getPcu());
                        online.setDateStr(gameReportData.getDateStr());
                        onlineList.add(online);

                        EntityDuration duration = new EntityDuration();
                        duration.setAverageDuration(gameReportData.getAvgOnlineTime());
                        duration.setAverageLogin(gameReportData.getAvgLoginTime());
                        duration.setDateStr(gameReportData.getDateStr());
                        durationList.add(duration);

                        EntityRemain remain = new EntityRemain();
                        remain.setDateStr(gameReportData.getDateStr());
                        remain.setDevice2Remain(gameReportData.getTheDevice2Left());
                        remain.setDevice3Remain(gameReportData.getTheDevice3Left());
                        remain.setDevice7Remain(gameReportData.getTheDevice7Left());
                        remain.setUser2Remain(gameReportData.getThe2Left());
                        remain.setUser3Remain(gameReportData.getThe3Left());
                        remain.setUser7Remain(gameReportData.getThe7Left());
                        remainList.add(remain);
                    }
                }

                // 取渠道相关数据
                List<String> channelnamelist = biChannelManager.findByQuery("select name from EntityBiChannel where length(platName)>0");

                if (channelnamelist == null) {
                    channelnamelist = new ArrayList<>();
                }
                Map<String, List<GameReportManager.GameReportData>> tmpchannelSource = new HashMap<>(50);
                tmpchannelSource.put("0",new ArrayList<GameReportManager.GameReportData>());
                for (GameReportManager.GameReportData p : detailChannelDataList) {
                    String platformid = p.getPlatformId();
                    List<GameReportManager.GameReportData> tmp = tmpchannelSource.get(platformid);
                    if (tmp == null) {
                        tmp = new ArrayList<>();
                        tmpchannelSource.put(platformid, tmp);
                    }
                    tmp.add(p);
                    tmpchannelSource.get("0").add(p);
                }
                for (Map.Entry<String, List<GameReportManager.GameReportData>> entry : tmpchannelSource.entrySet()) {
                    String platformid = entry.getKey();
                    List<GameReportManager.GameReportData> value = entry.getValue();

                    EntityChannelSource channelSource = channelSources.get(platformid);
                    if (channelSource == null) {
                        channelSource = new EntityChannelSource();
                        channelSources.put(platformid, channelSource);
                    }

                    int sumActive = 0;
                    int sumNew = 0;
                    Map<String, Integer> deviceActive = channelSource.getDeviceActive();
                    Map<String, Integer> newAddPlayer = channelSource.getNewAddPlayer();
                    for (GameReportManager.GameReportData p : value) {
                        String channelName = p.getChannelName();
                        int activeDevice = p.getActiveDevice();
                        int newPlayer = p.getNewUser();

                        if (channelnamelist.contains(channelName)) {
                            deviceActive.put(channelName, activeDevice);
                            newAddPlayer.put(channelName, newPlayer);
                        } else {
                            sumActive += activeDevice;
                            sumNew += newPlayer;
                        }
                    }

                    if (sumActive > 0) {
                        deviceActive.put("其它", sumActive);
                    }
                    if (sumNew > 0) {
                        newAddPlayer.put("其它", sumNew);
                    }
                }
            }

            result0.put("res", "0");
            result0.put("entityBanner", entityBanners.get("0"));
            result0.put("newAddList", newAdds.get("0"));
            result0.put("activeList", actives.get("0"));
            result0.put("payList", pays.get("0"));
            result0.put("onlineList", onlines.get("0"));
            result0.put("durationList", durations.get("0"));
            result0.put("remainList", remains.get("0"));
            result0.put("channelSource", channelSources.get("0"));

            result2.put("entityBanner", entityBanners.get("2"));
            result2.put("newAddList", newAdds.get("2"));
            result2.put("activeList", actives.get("2"));
            result2.put("payList", pays.get("2"));
            result2.put("onlineList", onlines.get("2"));
            result2.put("durationList", durations.get("2"));
            result2.put("remainList", remains.get("2"));
            result2.put("channelSource", channelSources.get("2"));

            result3.put("entityBanner", entityBanners.get("3"));
            result3.put("newAddList", newAdds.get("3"));
            result3.put("activeList", actives.get("3"));
            result3.put("payList", pays.get("3"));
            result3.put("onlineList", onlines.get("3"));
            result3.put("durationList", durations.get("3"));
            result3.put("remainList", remains.get("3"));
            result3.put("channelSource", channelSources.get("3"));

            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
        }
    }
}